
const requests = require('../../config/request');
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        menuTapCurrent: 0,
        currentLeft: 0, //左侧选中的下标
        selectId: "item0",  //当前显示的元素id
        scrollTop: 0, //到顶部的距离
        serviceTypes: [], //项目列表数据
        staffList: [],
        coupons: [],
        shade: false,
        shop_id: '',
        count: 0,
        sum: 0,
        specs_box_status: false,
        cart_status: false,
        winHeight: 0, // 屏幕高度
        list: [], // 数据列表
        cards: [],
        anchorType: 'i' + 1, // 左侧类型锚点位置
        anchorData: 'i' + 1, // 右侧数据锚点位置
        address: '',
        shop: [],
        cate: [],
        menu: [],
        loading: false,
        specification: [],
        specification_attributes: [],
        selected_specification: {
            name: [],
            goods_name: '',
            specificationId: [],
            num: 1,
            attributeId: 0,
            name_string: '',
            unit_price: '0',
            price: 0,
            image: '',
            item: null
        },
        submit: false,
        settlementText: '去结算',
        pageFirstShow: true,
    },
    menuTap: function (e) {
        var current = e.currentTarget.dataset.current;//获取到绑定的数据
        //改变menuTapCurrent的值为当前选中的menu所绑定的数据
        this.setData({
            menuTapCurrent: current
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.getSystemInfo({
            success: (res) => {
                //屏幕的宽度/屏幕的高度 = 微信固定宽度(750)/微信高度
                //   that.setData({
                //     // 80是上面盒子高度
                //     winHeight: res.windowHeight - (res.windowWidth * 80 / 750)
                //   })
                this.setData({
                    winHeight: res.windowHeight - (res.windowWidth * 450 / 750)
                })
            }
        });
        // 初始化数据
        this.setData({
            // list: createDataList(),
            shop_id: options.shop_id
        });

        this.getShop()
    },
    typeClick(e) { // 左侧tab单击事件
        let _index = e.currentTarget.dataset.index;
        let _id = e.currentTarget.dataset.id;
        this.changeCheck(_index);
        this.setData({ anchorData: 'i' + _id });
    },
    changeCheck(index) { // 左侧tab切换
        let curTypeList = this.data.list;
        curTypeList.map((item) => {
            item.check = false;
        });
        curTypeList[index].check = true;
        this.setData({ list: curTypeList });
    },
    returnIndex(id) { // 根据ID查找元素并返回索引
        let list = this.data.list;
        let reIndex = 0;
        list.forEach((item, index) => {
            if (item.id == id) {
                reIndex = index;
            }
        });
        return reIndex;
    },
    dataScroll(e) { // 右侧滚动
        let query = wx.createSelectorQuery();
        query.selectAll('.list-item').boundingClientRect(rects => {
            rects.forEach(item => {
                let top = item.top;
                let bottom = item.bottom;
                if (top >= 0 && bottom >= 0) { // top 和 bottom为负数就不考虑 锚点触发
                    if (top <= this.data.winHeight && bottom <= this.data.winHeight) { // 距离顶部和距离底部都小于屏幕高度时触发
                        this.setData({ anchorType: item.id });
                        this.changeCheck(this.returnIndex(item.id.slice(1, item.id.length)));
                    }
                }
            });
        }).exec();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        if(this.data.pageFirstShow !== true ) {
            this.getShop();
        }
        this.setData({pageFirstShow: false})
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.setData({loading: false})
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    add(e) {
        let item = e.currentTarget.dataset.item
        if (!item) {
            return;
        }
        
        if(item.specification_property_id === undefined) {
            item.specification_property_id = 0;
        }
        this.updateCard(item, (Number(item.num) || 0) + 1)
    },
    sub(e) {
        let item = e.currentTarget.dataset.item
        if (!item) {
            return;
        }
        if (item.num < 1) {
            return;
        }
        if(item.specification_property_id === undefined) {
            item.specification_property_id = 0;
        }
        this.updateCard(item, (Number(item.num) || 0) - 1)
    },
    updateCard(item, number) {
        if (item === null) {
            // 清空购物车
            return;
        }
        wx.showLoading({
            title: '请求中',
        })
        item.type = item.num > number ? 'sub' : 'add';
        let formData = {
            menu_id: item.id,
            price_shop: item.price_shop,
            price_market: item.price_market,
            specification_property_id: item.specification_property_id || 0,
            num: number,
            type: item.type,
            shop_id: this.data.shop_id,
        }
        requests.cartSet(formData).then(() => {
            wx.hideLoading()
            let lists = [].concat(this.data.list);
            lists.map((_item) => {
                if (_item.id === item.cate_id1) {
                    _item.list.map((__item) => {
                        if (__item.id === item.id) {
                            __item.num = number;
                        }
                    })
                }
            })

            this.setData({ list: lists })

            let updateCard = false;
            let index = -1;
            let cards = [].concat(this.data.cards);
            cards.map((_item, _index) => {
                if (item.id == _item.id && _item.specification_property_id == item.specification_property_id) {
                    updateCard = true;
                    if (number > 0) {
                        _item.num = number;
                    } else {
                        index = _index
                    }
                }
            })
            if (index >= 0) {
                cards.splice(index, 1);
            }

            if (!updateCard) {
                cards.push(Object.assign(item, formData, {
                    num: number,
                }))
            }

            this.setData({ cards })

            this.changeCards();
        })

    },
    getShop() {
        wx.showLoading({
            title: '加载中',
        })
        requests.shop({ shop_id: this.data.shop_id })
            .then(({ address, shop, cate, menu, cart }) => {
                wx.hideLoading()
                let menuLists = []
                let tempMenu = {}
                let cards = []
                Array.isArray(cart) && cart.forEach((item) => {
                    cards.push(item)
                })
                this.setData({ cards, shop })
                this.changeCards();
                // 把菜单转成字典
                Array.isArray(menu) && menu.forEach((item) => {
                    if (!tempMenu[item.cate_id1]) {
                        tempMenu[item.cate_id1] = []
                    }
                    tempMenu[item.cate_id1].push(item)
                })
                // 处理数据结构
                Array.isArray(cate) && cate.forEach((item, index) => {
                    menuLists.push({
                        id: item.id,
                        name: item.cate_name,
                        check: index === 0,
                        list: tempMenu[item.id] || []
                    })
                })
                this.setData({
                    address, list: menuLists, menu: tempMenu, loading: true
                })
            })
    },
    changeCards() {
        let count = 0;
        let sum = 0;
        this.data.cards.forEach((item) => {
            count += parseInt(item.num)
            sum = Number(sum) + Number(parseFloat(item.price_shop * item.num).toFixed(2))
        });
        let submit = sum > 0;
        let settlementText = '去结算';
        let fee_start = this.data.shop.fee_start || 0;
        if (fee_start > 0 && sum < fee_start) {
            submit = false;
            settlementText = '差' + (parseFloat(fee_start - sum).toFixed(2)) + '起送';
        }
        this.setData({count, sum, submit, settlementText})
    },

    makePhoneCall(e) {
        let phone = e.currentTarget.dataset.phone;
        if (!phone) {
            return;
        }
        wx.makePhoneCall({
            phoneNumber: phone
        })
    },

    updateCartStatus() {
        let status = !this.data.cart_status
        this.setData({
            cart_status: status,
            shade: status,
        })
    },
    updateSpecsBoxStatus(e) {
        let status = !this.data.specs_box_status;
        if (status === false) {
            this.setData({
                specs_box_status: status,
                shade: status,
            })
            return;
        }
        let item = e.currentTarget.dataset.item
        requests.specification({ goods_id: item.id }).then(({ specification, attributes }) => {
            let name = []
            let specificationId = []
            for (const i in specification) {
                let values = specification[i].values;
                for (const j in values) {
                    specification[i].values[j].selected = false
                    if (j == 0) {
                        name.push(values[j].name);
                        specificationId.push(values[j].id);
                        specification[i].values[j].selected = true
                    }
                }
            }
            let attributeDict = {}
            Array.isArray(attributes) && attributes.forEach((item) => {
                attributeDict[item.specification_name.sort().join('-')] =  item;
            })


            this.setData({ specification, specification_attributes: attributeDict })
            const { unit_price, attribute_id, image } = this.getUnitPriceAndAttributeIdAndImage(name)
            this.setData({
                specs_box_status: status,
                shade: status,
                selected_specification: Object.assign(this.data.selected_specification, {
                    name: name,
                    goods_name: item.food_name,
                    specificationId: specificationId,
                    item: item,
                    num: 1,
                    image: image || item.img_path,
                    attributeId: attribute_id,
                    name_string: name.join(' / '),
                    price: unit_price,
                    unit_price
                })
            })
        })
    },

    selectedSpecification(e) {
        let data = e.currentTarget.dataset;
        let specification = this.data.specification;
        let specificationId = [];
        let name = []
        let values = specification[data.parentIndex].values;
        for (const j in values) {
            specification[data.parentIndex].values[j].selected = false
        }
        specification[data.parentIndex].values[data.index].selected = true;

        for (const i in specification) {
            let values = specification[i].values;
            for (const j in values) {
                let value = values[j];
                if (value.selected) {
                    name.push(values[j].name);
                    specificationId.push(values[j].id);
                }
            }
        }

        this.setData({ specification })

        const { unit_price, attribute_id, iamge } = this.getUnitPriceAndAttributeIdAndImage(name)
        this.setData({
            selected_specification: Object.assign(this.data.selected_specification, {
                name: name,
                specificationId: specificationId,
                num: 1,
                image: iamge || this.data.selected_specification.item.img_path,
                attributeId: attribute_id,
                name_string: name.join(' / '),
                price: unit_price,
                unit_price,
            })
        })
    },

    getUnitPriceAndAttributeIdAndImage(name) {
        let specificationName = name.sort().join('-');
        let attribute = this.data.specification_attributes[specificationName];
        if(!attribute) {
            return { unit_price: 0, attribute_id: 0, image: '' };
        }
        console.log(attribute)
        return { unit_price: parseFloat(attribute.price).toFixed(2), attribute_id: attribute.id, image: attribute.image_url || '' };

        
    },
    clickShade() {
        this.setData({
            cart_status: false,
            specs_box_status: false,
            shade: false,
        })
    },
    setSpecificationCartNumber(e) {
        let number = Number(e.currentTarget.dataset.number || 0);
        if (number <= 0) {
            return;
        }
        this.setData({
            selected_specification: Object.assign(this.data.selected_specification, {
                num: number,
                price: parseFloat(number * this.data.selected_specification.unit_price).toFixed(2)
            })
        })
    },
    specificationAddCard() {
        if (!this.data.specs_box_status) {
            return;
        }
        let item = this.data.selected_specification.item;
        item.specification_name = this.data.selected_specification.name_string;
        item.specification_property_id = this.data.selected_specification.attributeId;
        item.price_market = this.data.selected_specification.unit_price;
        item.price_shop = this.data.selected_specification.unit_price;
        let number = this.data.selected_specification.num;
        for (const i in this.data.cards) {
            let cart = this.data.cards[i];
            if (cart.id == item.id && cart.specification_property_id == item.specification_property_id) {
                number = number + Number(cart.num)
                break;
            }
        }
        this.updateCard(item, number);
        this.updateSpecsBoxStatus()
    },
    clearCart() {
        requests.cartDel({ shop_id: this.data.shop_id }).then(() => {
            let lists = this.data.list;
            lists.map((item) => {
                item.list.map((_item) => {
                    _item.num = 0;
                })
            })
            this.setData({ cards: [],  list: lists})
            this.changeCards();
        })
    },
    settlement() {
        if(this.data.submit === false) {
            return;
        }
        wx.navigateTo({
          url: '../order/confirm/index?shop_id=' + this.data.shop_id,
        })
    }
})